package cn.restcloud.example.controller.mongo;

import java.util.ArrayList;
import java.util.List;
import org.bson.BsonDocument;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;

/**
 * 链接mongodb并进行数据报表的示例代码
 * @author Thinkpad
 *
 */
public class MongoClientReportRest {
	private MongoClient client;
	
	public List<Document> report() throws Exception{
		String dbName="RC_APILOG_2020-03-12";
		String collectionName="P_ActionUrlAccessLog";
		String startDayStr="2020-03-10";
        MongoCollection<Document> mc=this.getClient().getDatabase(dbName).getCollection(collectionName);
        List<Bson> filters=new ArrayList<Bson>();
        filters.add(BsonDocument.parse("{'$match':{'accessDate':{$gt:'"+startDayStr+"'}}}"));
        filters.add(BsonDocument.parse("{$group : {_id : '$accessDate', total : {$sum : 1}}}"));
        filters.add(BsonDocument.parse("{'$sort':{total:-1}}"));
        filters.add(BsonDocument.parse("{ $limit : 100 }"));
        
        AggregateIterable<Document> aggdocs=mc.aggregate(filters);
        List<Document> docs=new ArrayList<Document>();
        for(Document doc:aggdocs) {
        	Document newdoc=new Document();
        	newdoc.putAll((Document)doc.get("_id")); //把id中的字段放入到新的newdoc中
        	newdoc.put("total", doc.get("total")); //取统计结果
        	docs.add(newdoc);
        }
        return docs;
	}
	
	/**
	 * 获取链接
	 * @return
	 */
	public MongoClient getClient() {
		if(this.client==null) {
			 MongoClientURI connectionString = new MongoClientURI("mongodb://admin:pass@192.168.1.1/admin");  
			 this.client=new MongoClient(connectionString);
		}
		return client;
	}
	
}
